﻿using AJWPFAdmin.Core;
using AJWPFAdmin.Core.Components.AJFilePicker.ViewModels;
using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Components.ViewModels;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Excel;
using AJWPFAdmin.Core.ExtensionMethods;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Core.Validation;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Services.EF;
using AngleSharp.Css;
using Azure;
using DocumentFormat.OpenXml.Office2010.Drawing.Charts;
using Masuit.Tools;
using Masuit.Tools.Core.Validator;
using Masuit.Tools.Systems;
using MaterialDesignExtensions.Model;
using MaterialDesignThemes.Wpf;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.X509;
using Prism.Commands;
using Prism.Events;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Yitter.IdGenerator;
using static AJWPFAdmin.Core.ExceptionTool;

namespace EntranceGuardManager.Modules.Main.ViewModels
{
    public class EmiRiseRecordFormViewModel : AnnotationValidationViewModel, IDialogAware
    {
        private string _dialogTitle;
        public string DialogTitle
        {
            get { return _dialogTitle; }
            set { SetProperty(ref _dialogTitle, value); }
        }

        private bool _loading;
        public bool Loading
        {
            get { return _loading; }
            set { SetProperty(ref _loading, value); }
        }

        private EmiRiseRecord _form;

        private string _carNo;
        [Comment("车牌号")]
        [StringLength(120, ErrorMessage = "{0}超长:{1}")]
        public string CarNo
        {
            get => _carNo;
            set
            {
                SetProperty(ref _carNo, value);
                SaveCmd.RaiseCanExecuteChanged();
            }
        }

        private int? _overproofVerifyResult;
        [Comment("超标核实结果")]
        public int? OverproofVerifyResult
        {
            get => _overproofVerifyResult;
            set
            {
                SetProperty(ref _overproofVerifyResult, value);
                SaveCmd.RaiseCanExecuteChanged();
            }
        }

        private string _exceedInfo;
        [Comment("超标原因")]
        [StringLength(500, ErrorMessage = "{0}超长:{1}")]
        public string ExceedInfo
        {
            get => _exceedInfo;
            set
            {
                SetProperty(ref _exceedInfo, value);
                SaveCmd.RaiseCanExecuteChanged();
            }
        }






        private DelegateCommand _saveCmd;
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSaveCmdAsync, CanExecuteSaveCmd));

        async void ExecuteSaveCmdAsync()
        {
            if (!ValidateModel())
            {
                SaveCmd.RaiseCanExecuteChanged();

                AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
                {
                    Title = "提示",
                    Message = "表单校验失败,请检查所填数据",
                    Detail = string.Join(";", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString()))
                });
                return;
            }

            Loading = true;

            var carNo = CarNo;
            _form.CarNo = carNo;

            if (_form.Id == 0)
            {
                if (db.EmiRiseRecords.Any(p => p.CarNo == carNo))
                {
                    ExceptionTool.FriendlyError("车牌号已存在", dialogId: DialogIds.DialogWindow);
                    return;
                }
                _form.OverproofVerifyResult = OverproofVerifyResult;
                _form.ExceedInfo =ExceedInfo;
                _form.Id = YitIdHelper.NextId();
                _form.StartTime = DateTime.Now;
                db.EmiRiseRecords.Add(_form);
            }
            else
            {

                if (_form.CarNo != carNo && db.EmiRiseRecords.Any(p => p.CarNo == carNo))
                {
                    ExceptionTool.FriendlyError("车牌号已存在", dialogId: DialogIds.DialogWindow);
                    return;
                }
                _form.OverproofVerifyResult = OverproofVerifyResult;
                //_form.StartTime = DateTime.Now;
                db.Entry(_form).State = EntityState.Modified;
            }

            await db.SaveChangesAsync();
            var carInfo= db.Cars.AsNoTracking().FirstOrDefault(p => p.CarNo == carNo);
            //上传排放超标信息
            await _appointSvc.API.UploadEmiRiseRecordInfoAsync(new EmiRiseRecordParams
            {
                CarInfo = carInfo,
                EmiRiseRecord = _form
            });


            Loading = false;

            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }

        bool CanExecuteSaveCmd()
        {
            return !HasErrors;
        }

        public string Title => string.Empty;

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            parameters.TryGetValue<EmiRiseRecord>("data", out var data);

            parameters.TryGetValue<MaterialType>("type", out var type);

            if (data != null)
            {
                _form = data;

                CarNo = _form.CarNo;
                OverproofVerifyResult = _form.OverproofVerifyResult;
            }
            else
            {
            
            }

            DialogTitle = data == null ? $"新增排放超标" : $"编辑 {data.CarNo}";
        }

        private DbService db;
        private AJGlobalExceptionResolvedEvent _globalExceptionEvt;
        private AppointAPISvc _appointSvc;
        public EmiRiseRecordFormViewModel(DbService dbIns, IEventAggregator eventAggregator, AppointAPISvc appointAPISvc)
        {
            _appointSvc = appointAPISvc;
            _form = new EmiRiseRecord {  };
            _globalExceptionEvt = eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>();
            _globalExceptionEvt.Subscribe(() =>
            {
                Loading = false;
            });
            db = dbIns;
        }
    }
}
